//
//  XLSwitchView.m
//  Home
//
//  Created by liusanchun on 14-8-15.
//  Copyright (c) 2014年 liusanchun. All rights reserved.
//

#import "XLSwitchView.h"
#define NAVIGATION_BACKGROUND_COLOR [UIColor colorWithRed:27.0f/255 green:195.0f/255 blue:238.0f/255.0 alpha:1.0f]
#define ScreenWidth [UIScreen mainScreen].bounds.size.width

#define ScreenHeight [UIScreen mainScreen].bounds.size.height

#define Navigation_Bar_Height 44

#define Tab_Bar_Height 30

#define News_TableView_Y 108.0f
static const CGFloat XLTopHeight = 64;
static const CGFloat XLTabFontSize = 14.0f;
static const CGFloat xlTabMargin = 8;

@interface XLSwitchView ()<UIScrollViewDelegate>

@end

@implementation XLSwitchView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self setup];
    }
    return self;
}

- (void)setup
{
    _isCreateUserInterface = NO;
    _vcArray = [[NSMutableArray alloc] init];
    
    _topScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, ScreenWidth, _topWidth==0?XLTopHeight:_topWidth)];
    _topScrollView.showsHorizontalScrollIndicator = NO;
    _topScrollView.showsVerticalScrollIndicator = NO;
    _topScrollView.delegate = self;
    _topScrollView.pagingEnabled = NO;
    _topScrollView.backgroundColor = UIColorFromRGB(0xf1f1f1);
    _topScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self addSubview:_topScrollView];
    
    _contentScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f, XLTopHeight, ScreenWidth, self.frame.size.height - XLTopHeight)];
    _contentScrollView.delegate = self;
    _contentScrollView.showsVerticalScrollIndicator = NO;
    _contentScrollView.showsHorizontalScrollIndicator = NO;
    _contentScrollView.pagingEnabled = YES;
    _contentScrollView.backgroundColor = [UIColor clearColor];
    _contentScrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth;
    [self addSubview:_contentScrollView];
    
}

- (void)layoutSubviews
{
    if (_isCreateUserInterface) {
        _contentScrollView.contentSize = CGSizeMake(ScreenWidth*[_vcArray count], 0);
        
        for (int index = 0; index < [_vcArray count]; index++) {
            UIViewController *vc = [_vcArray objectAtIndex:index];
            vc.view.frame = CGRectMake(index*ScreenWidth, 0.0f, _contentScrollView.bounds.size.width, _contentScrollView.bounds.size.height);
        }
        _isCreateUserInterface = NO;
    }
}
/**
 *  创建子视图
 */
- (void)createUserInterface
{
    NSUInteger number = [self.delegate numberOfItemsInSwitchView:self];
    for (int index = 0; index < number; index++) {
        UIViewController *vc = [self.delegate switchView:self
                                          withViewOfItem:index];
        [_vcArray addObject:vc];
        [_contentScrollView addSubview:vc.view];
    }
    [self createTabs];
    self.isCreateUserInterface = YES;
    
    //创建完子视图UI才需要调整布局
    [self setNeedsLayout];
    
}

- (void)createTabs
{
    
    _shadowView = [[UIView alloc] init];
    _shadowView.backgroundColor = _inecolor;
    
    [_topScrollView addSubview:_shadowView];
    
    //顶部tabbar的总长度
    CGFloat topScrollViewContentWidth = xlTabMargin;
    //每个tab偏移量
    CGFloat xOffset = 0;
    for (int index = 0; index < [_vcArray count]; index++) {
        UIViewController *vc = _vcArray[index];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        CGSize textSize = [vc.title sizeWithFont:[UIFont systemFontOfSize:XLTabFontSize]
                               constrainedToSize:CGSizeMake(_topScrollView.bounds.size.width, _topWidth==0?XLTopHeight:_topWidth)
                                   lineBreakMode:NSLineBreakByTruncatingTail];
//        if (ScreenWidth > 320) {
//            textSize.width = textSize.width*1.35;
//         }
      
        if(index == 0){
            [button setFrame:CGRectMake(0,10,
                                        self.btnWidth, _topWidth==0?XLTopHeight:_topWidth-10)];
        }else{
            [button setFrame:CGRectMake(topScrollViewContentWidth,10,
                                        self.btnWidth, _topWidth==0?XLTopHeight:_topWidth-10)];
        }
        xOffset += textSize.width;
        topScrollViewContentWidth += button.frame.size.width;
////        textSize.width = ScreenWidth/[_vcArray count];
//        //累计每个tab文字的长度
////        topScrollViewContentWidth +=   textSize.width;
//        [button setFrame:CGRectMake(index==0?0:textSize.width*index,0,
//                                    textSize.width, XLTopHeight)];
        
        
        //计算下一个tab的x偏移量
//        xOffset = index==0?0:textSize.width*index;
        [button setTag:index + 100];
        if (index == 0) {
            _shadowView.frame = CGRectMake(0, (_topWidth==0?XLTopHeight:_topWidth) - 2.0f,button.frame.size
                                           .width, 2.0f);
            button.selected = YES;
            _selectedTabIndex = (index + 100);
        }
        [button setTitle:vc.title forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:XLTabFontSize];
        button.backgroundColor = [UIColor clearColor];
        [button addTarget:self
                   action:@selector(tabSelected:)
         forControlEvents:UIControlEventTouchUpInside];
        [button setTitleColor:[UIColor blackColor]
                     forState:UIControlStateNormal];
        [button setTitleColor:_btncolor
                     forState:UIControlStateSelected];
        NSLog(@"w:%f  x:%f",button.frame.size.width,button.frame.origin.x);
        [_topScrollView addSubview:button];
    }
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(0, _shadowView.frame.origin.y+2, ScreenWidth, 0.5)];
    lable.backgroundColor = colorBG;
    [_topScrollView addSubview:lable];
    //设置顶部滚动视图的内容总尺寸
    _topScrollView.scrollEnabled = NO;
//    _topScrollView.contentSize = CGSizeMake(topScrollViewContentWidth, XLTopHeight);
}

- (void)tabSelected:(UIButton*)sender
{
    [self.delegate ScrollAction:sender.tag];
    [self adjustCenter:sender];
    for (int i = 0 ; i<[_vcArray count]; i++) {
        UIButton *button = (UIButton*)[_topScrollView viewWithTag:i+100];
        button.selected = NO;
    }
    sender.selected = YES;
    [UIView animateWithDuration:0.25 animations:^{

        [_shadowView setFrame:CGRectMake(sender.frame.origin.x, (_topWidth==0?XLTopHeight:_topWidth) - 2.0f, sender.frame.size.width, _shadowView.frame.size.height)];

        
    } completion:^(BOOL finished) {
        if (finished) {
             [_contentScrollView setContentOffset:CGPointMake((sender.tag - 100)*self.bounds.size.width, 0)
                                        animated:YES];
        }
    }];
}
-(void)initViewLoaction{
    int tag = 100;
    UIButton *button = (UIButton *)[_topScrollView viewWithTag:tag];
    [self tabSelected:button];
}
- (void)adjustCenter:(UIButton*)sender
{
    if (sender.frame.origin.x - _topScrollView.contentOffset.x > self.bounds.size.width - (xlTabMargin+sender.bounds.size.width)) {
//        [_topScrollView setContentOffset:CGPointMake(sender.frame.origin.x - (_topScrollView.bounds.size.width- (xlTabMargin+sender.bounds.size.width)), 0)  animated:YES];
        NSLog(@"w:%f  x:%f ScreenWidth:%f",_topScrollView.frame.size.width,_topScrollView.frame.origin.x,ScreenWidth);

    }
    
    if (sender.frame.origin.x - _topScrollView.contentOffset.x < xlTabMargin) {
//        [_topScrollView setContentOffset:CGPointMake(sender.frame.origin.x - xlTabMargin, 0)  animated:YES];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == _contentScrollView) {
        //调整顶部滑条按钮状态
        int tag = (int)scrollView.contentOffset.x/self.bounds.size.width + 100;
        UIButton *button = (UIButton *)[_topScrollView viewWithTag:tag];
         [self tabSelected:button];
        [self.delegate ScrollAction:tag];
    }

}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect
 {
 // Drawing code
 }
 */

@end
